<template>
    <view class="container">
        <!-- 搜索栏 -->
        <view class="search-section">
            <!-- 定位信息行 -->
            <view class="search-row">
                <image v-if="!location" src="/static/location-icon.png" mode="aspectFit" style="width: 20px; height: 20px;"></image>
                <text>{{ location || '合肥市' }}</text>
                <button @click="navigateToSelectLocation">切换位置</button>
            </view>
            <!-- 企业类型选择行 -->
            <view class="search-row">
                <text>企业类型：</text>
                <picker :range="companyTypeOptions" v-model="selectedCompanyType" @change="onCompanyTypeChange">
                    <view class="picker-view">
                        {{ selectedCompanyType }}
                        <image src="/static/arrow-down.png" mode="aspectFit" style="width: 15px; height: 15px;"></image>
                    </view>
                </picker>
            </view>
            <!-- 距离选择行 -->
            <view class="search-row">
                <text>选择距离：</text>
                <picker :range="distanceOptions" v-model="selectedDistance" @change="onDistanceChange">
                    <view class="picker-view">
                        {{ selectedDistance }}
                        <image src="/static/arrow-down.png" mode="aspectFit" style="width: 15px; height: 15px;"></image>
                    </view>
                </picker>
            </view>
            <!-- 关键字输入行 -->
            <view class="search-row">
                <input v-model="keyword" placeholder="输入企业名称等关键字" />
            </view>
            <!-- 搜索按钮行 -->
            <view class="search-row">
                <button @click="searchNearbyCompanies">立即搜索</button>
            </view>
        </view>
        <!-- 定位失败提示 -->
        <view v-if="isLocationFailed" class="location-failed-tip">
            <text>获取定位失败，请检查定位权限或网络设置。</text>
            <button @click="fetchLocation">重新获取定位</button>
        </view>
        <!-- 百度地图展示 -->
        <view id="baiduMap" style="width: 100%; height: 80vh;"></view>
    </view>
</template>

<script setup>
import { ref, onMounted, getCurrentInstance } from 'vue';

// 获取全局配置
const { appContext } = getCurrentInstance();
const $tab = appContext.config.globalProperties.$tab;

// 定位信息
const location = ref('');
const latitude = ref(31.86);
const longitude = ref(117.28);

// 距离选项
const distanceOptions = ref(['1km', '2km', '5km', '10km']);
const selectedDistance = ref('1km');

// 企业类型选项
const companyTypeOptions = ref(['餐饮', '零售', '服务', '娱乐']);
const selectedCompanyType = ref('餐饮');

// 关键字输入
const keyword = ref('');

// 百度地图对象
let map;

// 定位是否失败
const isLocationFailed = ref(false);

// 获取定位
const fetchLocation = async () => {
    try {
        const { latitude: lat, longitude: lon } = await uni.getLocation({
            type: 'wgs84'
        });
        latitude.value = lat;
        longitude.value = lon;
        location.value = `纬度: ${latitude.value}, 经度: ${longitude.value}`;
        isLocationFailed.value = false;
        // 初始化百度地图
        initBaiduMap();
    } catch (e) {
        console.error('获取定位失败:', e);
        location.value = '';
        isLocationFailed.value = true;
        initBaiduMap();
    }
};

// 初始化百度地图
const initBaiduMap = () => {
    // 创建地图实例
    map = new BMap.Map('baiduMap');
    // 创建点坐标
    const point = new BMap.Point(longitude.value, latitude.value);
    // 初始化地图，设置中心点和缩放级别
    map.centerAndZoom(point, 15);
    // 添加地图控件
    map.addControl(new BMap.NavigationControl());
};

// 选择距离
const onDistanceChange = (e) => {
    selectedDistance.value = distanceOptions.value[e.detail.value];
    console.log('选择的距离:', selectedDistance.value);
};

// 选择企业类型
const onCompanyTypeChange = (e) => {
    selectedCompanyType.value = companyTypeOptions.value[e.detail.value];
    console.log('选择的企业类型:', selectedCompanyType.value);
};

// 搜索附近企业
const searchNearbyCompanies = () => {
    // 这里模拟从后端获取数据，实际使用时需要替换为真实的接口请求
    const mockData = [
        {
            name: '企业 A',
            latitude: latitude.value + 0.001,
            longitude: longitude.value + 0.001
        },
        {
            name: '企业 B',
            latitude: latitude.value - 0.001,
            longitude: longitude.value - 0.001
        }
    ];

    // 清除之前的标记
    map.clearOverlays();

    // 添加新的标记
    mockData.forEach((item) => {
        const point = new BMap.Point(item.longitude, item.latitude);
        const marker = new BMap.Marker(point);
        map.addOverlay(marker);

        // 添加标注信息
        const label = new BMap.Label(item.name, { offset: new BMap.Size(20, -10) });
        marker.setLabel(label);
    });
};

// 跳转到位置选择页面
const navigateToSelectLocation = () => {
    $tab.navigateTo(`/pages/company/selectLocation/selectLocation?latitude=${latitude.value}&longitude=${longitude.value}`);
};

// 监听返回的位置信息
const onShow = () => {
    const eventChannel = getCurrentPages()[getCurrentPages().length - 1].getOpenerEventChannel();
    eventChannel.on('returnLocation', (data) => {
        location.value = data.address;
        latitude.value = data.latitude;
        longitude.value = data.longitude;
        initBaiduMap();
    });
};

onMounted(() => {
    initBaiduMap();
    onShow();
});
</script>

<style scoped>
.container {
    padding: 10px;
    position: relative;
}

.search-section {
    position: absolute;
    top: 10px;
    left: 10px;
    right: 10px;
    background-color: rgba(255, 255, 255, 0.8);
    padding: 10px;
    border-radius: 5px;
    z-index: 1;
}

.search-row {
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    height: 40px;
}

.search-row button {
    margin-left: 10px;
}

.search-row text {
    margin-right: 10px;
}

.picker-view {
    display: flex;
    align-items: center;
}

.picker-view image {
    margin-left: 5px;
}

.search-row input {
    flex: 1;
    border: 1px solid #ccc;
    padding: 5px;
    border-radius: 3px;
    height: 30px;
}

.search-row button {
    width: 100%;
    height: 30px;
}

.location-failed-tip {
    text-align: center;
    margin-bottom: 10px;
}

.location-failed-tip text {
    color: red;
    margin-bottom: 5px;
    display: block;
}
</style>